#!/bin/bash

SERVER="http://38.147.172.96:8080"
NAME=$(hostname)
MANAGER_LOG="/os-user/manager.log"
MAX_LOG_SIZE=$((10*1024*1024))

mkdir -p /os-user

# 安装 sensors（如果未安装）
if ! command -v sensors &>/dev/null; then
    sudo apt update && sudo apt install -y lm-sensors
fi

# 获取状态
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
MEM=$(free | awk '/Mem/{printf("%.2f",$3/$2 * 100.0)}')
TEMP_RAW=$(sensors | awk '/Tctl:/ {printf("%.1f丨",$2)}')
TEMP="${TEMP_RAW%丨}"

# ------------------------
# 限制日志大小
# ------------------------
if [ -f "$MANAGER_LOG" ]; then
    FILE_SIZE=$(stat -c%s "$MANAGER_LOG")
    if [ "$FILE_SIZE" -gt "$MAX_LOG_SIZE" ]; then
        > "$MANAGER_LOG"  # 超过 10MB，直接清空
    fi
fi

# 上传状态
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
RESPONSE=$(curl -s -X POST -d "name=$NAME&cpu=$CPU&mem=$MEM&temp=$TEMP" "$SERVER/upload")

# 记录日志
echo "[$TIMESTAMP] 状态已上传: CPU=$CPU%, MEM=$MEM%, TEMP=$TEMP, 服务器响应: $RESPONSE" >> "$MANAGER_LOG"
